package com.cellulam.framework.datasource;

import com.cellulam.framework.core.context.AppContext;
import com.cellulam.framework.core.context.AppContextKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Stack;

/**
 * 数据源暂存 - 堆结构
 */
public class StackDataSource {

    private static final Logger logger = LoggerFactory.getLogger(StackDataSource.class);

    private static final ThreadLocal<Stack<String>> contextHolder = new ThreadLocal<>();

    public StackDataSource() {
        logger.info("StackDataSource init");
    }

    public static String getCurrentTargetKey() {
        if (isNotEmpty()) {
            return contextHolder.get().peek();
        }
        return null;
    }

    private static boolean isNotEmpty() {
        return contextHolder.get() != null && contextHolder.get().size() > 0;
    }

    public static void push(String dbName) {
        if (dbName == null) {
            throw new NullPointerException();
        }
        if (contextHolder.get() == null) {
            contextHolder.set(new Stack<>());
        }
        contextHolder.get().push(dbName);
        setCurrent(dbName);
    }

    public static String popupAndNext() {
        if (isNotEmpty()) {
            String poped = contextHolder.get().pop();
            logger.debug("popupAndNext current datasource#{}", poped);
            if (isNotEmpty()) {
                setCurrent(getCurrentTargetKey());
            }
            return poped;
        }
        logger.debug("popupAndNext current datasource is null");
        return null;
    }

    private static void setCurrent(String dbName) {
        DataSourceContextHolder.switchDataSource(dbName);
        AppContext.setValue(AppContextKey.CURRENT_DATA_SOURCE, dbName);
        logger.debug("set current datasource#{}", dbName);
    }

}
